<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Settings;
use App\Http\Services\Oss;

class UnionSettleCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'unionSettleCommand';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '对公结算docx生成';

    protected $manageCon = 'mysql';

    protected $apiCon = 'api';
    protected $unionTable = 'union';
    protected $unionSettleTable = 'union_settle';
    protected $systemConfigTable = 'system_config';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        set_time_limit(0);

        $yesterdayDate = date('Y-m-d', strtotime("-1 days"));
        $yesterdayStart = strtotime($yesterdayDate.' 00:00:00');
        $yesterdayEnd = strtotime($yesterdayDate.' 23:59:59');

        $now = time();

        //所有对公结算公会
        $logList = DB::connection($this->apiCon)->table($this->unionSettleTable)
            ->where('status', 0)
            ->get();
        $logList = objToArray($logList);

        $path = storage_path('docx/settle.docx');//模板的路径，word的版本最好是docx，要不然可能会读取不了，根据自己的模板位置调整

        //对公结算 应开票税率 文本
        $settleRate = DB::connection($this->apiCon)->table($this->systemConfigTable)
            ->where('key', 'union_settle_rate_msg')
            ->first();
        $settleRate = objToArray($settleRate);
        $settleRate = empty($settleRate['value']) ? '' : $settleRate['value'];

        foreach($logList as $val) {
            try {
                $settleNo = $val['id'];
                if($val['settle_date_st'] == $val['settle_date_ed']) {
                    $settleDate = date('Y-m-d', $val['settle_date_st']);
                }else{
                    $settleDate = date('Y-m-d', $val['settle_date_st']).'-'.date('Y-m-d', $val['settle_date_ed']);
                }
                $settlePrice = round($val['settle_kk']/10, 1);

                $settlePriceZh = $this->priceToString($settlePrice);

                $createDate = date('Y年m月d日', strtotime($val['created_at']));
                $unionCompany = $val['union_company'];
                $unionBankName = $val['union_bank_name'];
                $unionBankNo = $val['union_bank_no'];
    
                //生成word路径，根据自己的目录调整
                $filePath = storage_path('docx/'.$val['union_id'].'-'.strtotime($val['created_at']).'.docx');
                //声明一个模板对象、读取模板
                $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($path);
                //替换模板中的变量，对应word里的 ${test}
                $templateProcessor->setValue('settleNo', $settleNo);
                $templateProcessor->setValue('settleDate', $settleDate);
                $templateProcessor->setValue('settlePrice', $settlePrice);
                $templateProcessor->setValue('settleRate', $settleRate);
                $templateProcessor->setValue('settlePriceZh', $settlePriceZh);
                $templateProcessor->setValue('createDate', $createDate);
                $templateProcessor->setValue('unionCompany', $unionCompany);
                $templateProcessor->setValue('unionBankName', $unionBankName);
                $templateProcessor->setValue('unionBankNo', $unionBankNo);
                //生成新的word
                $templateProcessor->saveAs($filePath);

                //oss上传
                $settle_docx = $this->uploadOss(26, 'docx', $filePath);
                if(empty($settle_docx)) {
                    write_log('error_unionSettleCommand', '异常 oss上传', ['val'=>$val, 'filePath'=>$filePath]);
                    continue;
                }

                //更新数据库
                DB::connection($this->apiCon)->table($this->unionSettleTable)
                    ->where('id', $val['id'])
                    ->where('status', 0)
                    ->update(['status'=>1, 'settle_docx'=>$settle_docx]);

            }catch (\Exception $e){
                write_log('error_unionSettleCommand', '异常', ['val'=>$val, 'message'=>$e->getMessage(), 'line'=>$e->getLine()]);
                continue;
            }
        }
    }

    function uploadOss($type, $exts, $localFilePath) {
        //上传路径
        $upload_config =  curl_request(config('kkaudio.kkaudio_api') . "/inner/system/put_file_url", ['type'=>$type, 'exts'=>$exts], $contentType = 'urlencoded', $httpMethod = 'GET');
        if(empty($upload_config['data'][0]['uri'])) {
            return '';
        }
        $uri = $upload_config['data'][0]['uri'];
        $formatUri = ltrim($uri, '/');

        //上传
        $oss = new Oss();
        $ossRes = $oss->uploadFile($formatUri, $localFilePath);
        if (!$ossRes) {
            return '';
        }

        return '/'.$formatUri;
    }

    //金额转文字
    public function priceToString($num) {
        $result = '';
        $str1 = $this->convert_c_num(intval($num));
        if(!empty($str1)) {
            $result .= $str1.'元';
        }

        $num2 = (string) round(($num - intval($num))*100);
        if(strlen($num2) > 1) {
            $str2 = $this->convert_c_num($num2[0]);
            if(!empty($str2)) {
                $result .= $str2.'角';
            }
            $str3 = $this->convert_c_num($num2[1]);
            if(!empty($str3)) {
                $result .= $str3.'分';
            }
        }else if(strlen($num2) == 1) {
            $str3 = $this->convert_c_num($num2[0]);
            if(!empty($str3)) {
                $result .= $str3.'分';
            } 
        }

        return $result;
    }

    public function convert_c_num($num) {
        $a_num = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

        $c_num = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒' ,'捌' ,'玖');
    
        $j = array(0 => '', 1 =>'拾', 2 =>'佰', 3 =>'仟', 4 =>'万', 5 =>'拾', 6=> '佰', 7=>'仟');
    
        $r = strrev($num);

        $len = strlen($r) - 1;
    
        $desc = '';
        for($i = $len; $i >=0; $i--) {
            if ($r[$i]) {
                $desc .= $r[$i].$j[$i];
            } else {
                if ($i == 4) {
                    $desc .= '万';
                } else {
                    $desc .= '零';
                }
            }
        }

        return rtrim(str_replace($a_num, $c_num, $desc), '零');
    }


}
